<!--
  SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  SPDX-License-Identifier: MIT
-->
<div id="media"></div>

<script>
const pc = new RTCPeerConnection()
pc.ontrack = event => {
  if (event.track.kind === 'audio') {
    var el = document.createElement(event.track.kind)
    el.srcObject = new MediaStream(event.streams[0].getAudioTracks())
    document.getElementById('media').appendChild(el)
  }
}
pc.oniceconnectionstatechange = event => {
  console.log("connection", pc.iceConnectionState)
  if (pc.iceConnectionState == 'connected') {
    setInterval(statsReport, 1000)
  }
}
pc.onicecandidate = event => {
  if (event.candidate === null) {
    console.log("sdp", JSON.stringify(pc.localDescription))
  }
}
pc.addTransceiver('audio', {'direction': 'recvonly'})

const dc = pc.createDataChannel("upper")
dc.onmessage = event => {
  dc.send(event.data.toUpperCase())
}

pc.createOffer().then(d => pc.setLocalDescription(d)).catch(console.log)

const statsReport = async () => {
  const stats = await pc.getStats()
  var data = []
  await stats.forEach(item => {
    data.push(item)
  })
  console.log("stats", JSON.stringify(data))
}

</script>
